﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Disco.Ontology.Helper
{
    public struct EntitySetInfo
    {
        public string Name { get; set; }
        public Type Type { get; set; }
    }

    public static class OntologyContextHelper
    {
        public static IEnumerable<EntitySetInfo> GetEntitySetInfos()
        {
            foreach (var entitySet in typeof(OntologyContext).GetProperties())
            {
                Type entitySetType = entitySet.PropertyType;
                if (entitySetType.IsGenericType &&
                    entitySetType.GetGenericTypeDefinition().Name.Equals("DbSet`1"))
                {
                    var isPubliclyAccessible = entitySet.GetCustomAttributes(typeof(EntitySetAccessibilityAttribute), true)
                        .Count(attribute => ((EntitySetAccessibilityAttribute)attribute).Scope == AccessScope.Internal) // AccessScope.Public is default!
                        .Equals(0);
                    if (isPubliclyAccessible)
                    {
                        Type entityType = entitySetType.GetGenericArguments().FirstOrDefault();
                        if (null != entityType)
                        {
                            yield return new EntitySetInfo { Name = entitySet.Name, Type = entityType };
                        }
                    }
                }
            }
        }
    }
}
